# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

# 资金分类功能
# Fund ledger function

import os, sys

dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)
import utils.common.log as log
import time
import datetime
import utils.pgsql.pgchannel as pgchannel


def getYesterday(day_value=-1):
    '''
    获取前一天日期 2022-03-29
    :param day_value: 
    :return: 
    '''
    yesterday = datetime.date.today() + datetime.timedelta(day_value)
    return yesterday


def devidedinto_pay(pay, payflow, day_value): # 支付分成

    yesterday = getYesterday(day_value)
    obj = pay
    yesterdayList = obj.GetAllYesterDay(yesterday)
    if len(yesterdayList) == 0:
        log.logging.warning(
            "yesterday List is null : {} ".format(yesterdayList)
            )
        return
    log.logging.info(
        "yesterday ： {} ; yesterdayList len : {}".format(yesterday, yesterdayList)
    )
    for order in yesterdayList:
        channelId = order["channelId"]
        caseId = order["caseId"]
        obj_channel = pgchannel.PgChannel()
        channelInfo = obj_channel.channelInfo(channelId)
        caseInfo = obj_channel.caseInfo(caseId)
        if len(caseInfo) == 0:
            log.logging.error(
                "serious error : case info is null ; caseInfo : {}  channelInfo : {} !".format(
                    caseInfo, channelInfo
                )
            )
            continue
        print("channelInfo : {}".format(channelInfo))
        print("caseInfo : {}".format(caseInfo))
        orderdi_ = {
            "outTradeNo": order[
                "outTradeNo"
            ],  # VARCHAR(64) NOT NULL default '',    
            "transactionId": order[
                "transactionId"
            ],  # VARCHAR(256) NOT NULL default '',  
            "openId": order["openId"],  # VARCHAR(256) NOT NULL default '', 
            "productId": order[
                "productId"
            ],  # VARCHAR(256) NOT NULL default '',  
            "videoUrl": order["videoUrl"],  # VARCHAR(256) NOT NULL default '',  
            "duration": order["duration"],  # VARCHAR(256) NOT NULL default '',  
            "thumbImageUrl": order[
                "thumbImageUrl"
            ],  # VARCHAR(256) NOT NULL default '',  
            "channelId": order[
                "channelId"
            ],  # INTEGER NOT NULL default 0,  
            "channelInfo": "",  # VARCHAR(256) NOT NULL default '',  
            "caseId": order["caseId"],  # INTEGER NOT NULL default 0,  
            "caseName": "",  # VARCHAR(256) NOT NULL default '',  
            "operatorName": "",  # VARCHAR(256) NOT NULL default '',  
            "platformdi": 0,  # INTEGER NOT NULL default 0 ,     
            "enterprisesdi": 0,  # INTEGER NOT NULL default 0 ,     
            "individualsdi": 0,  # INTEGER NOT NULL default 0 ,     
            "createTime": order[
                "createTime"
            ],  # VARCHAR(64) NOT NULL default '',   
            "endTime": order[
                "endTime"
            ],  # VARCHAR(64) NOT NULL default '',     
            "totalFee": order[
                "totalFee"
            ],  # INTEGER NOT NULL default 0,  
            "cashFee": order["cashFee"],  # INTEGER NOT NULL default 0,   
            "updateTime": order["updateTime"],  # VARCHAR(32) NOT NULL default ''
        }

        if len(channelInfo) == 0:
            channel_proportion = 0
            orderdi_["channelInfo"] = caseInfo[0]["firmName"]  #  
        else:
            channel_proportion = int(channelInfo[0]["proportion"])
            orderdi_["channelInfo"] = channelInfo[0]["firmName"]

        orderdi_["caseName"] = caseInfo[0]["caseName"]
        orderdi_["operatorName"] = caseInfo[0]["firmName"]
        enterprise_proportion = int(caseInfo[0]["proportion"])
        platform_portion = 100 - int(channel_proportion) - int(enterprise_proportion)
        orderdi_["individualsdi"] = round(order["totalFee"] * channel_proportion / 100)
        if platform_portion == 0:
            orderdi_["enterprisesdi"] = order["totalFee"] - orderdi_["individualsdi"]
            orderdi_["platformdi"] = 0
        else:
            orderdi_["enterprisesdi"] = round(
                order["totalFee"] * enterprise_proportion / 100
            )
            orderdi_["platformdi"] = (
                order["totalFee"]
                - orderdi_["individualsdi"]
                - orderdi_["enterprisesdi"]
            )

        orderdi_["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        log.logging.info(
            "channel_proportion: {} ; firm_proportion: {} ; platform_portion : {}".format(
                channel_proportion, enterprise_proportion, platform_portion
            )
        )
        log.logging.info("orderdi_ : {} ".format(orderdi_))
        obj_payflow = payflow
        obj_payflow.addpayflow(orderdi_)

    obj_payflow = payflow
    today_pay = obj_payflow.GetAllTodayList(datetime.date.today())
    if len(yesterdayList) != len(today_pay):
        log.logging.info("today_pay len : {} ".format(len(today_pay)))
        log.logging.error("pay data update not the same ,please check !")
